<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Request;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $day;
    protected $day2;
    protected $day3 = 1; //往前几天
    public function __construct()
    {
        $this->day = date("Y-m-d 00:00:00", strtotime("-{$this->day3} day"));
        $this->day2 = date("Y-m-d 23:59:59", strtotime("-{$this->day3} day"));
    }

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
    // 统一结算收益   每日执行一次
    public function jiesuanAAA() {
        $adminmap = [
            'status' => "normal",
            'fee' => ['neq',0],
            'withdraw' => ['neq',0],
            'mechId' => ['neq',''],
        ];
        $stores = Db::name("admin")->where($adminmap)->select();
        foreach ($stores as $k => $v){
            if ($v['id'] == 1){
                continue;
            }
            $shouyi = 0;
            if ($v['mechId'] && $v['appId'] && $v['md5']){
                //sum 收益
                $map = [
                    'txnStatus' => 'S',
                    'status' => '1',
                    'mechId' => $v['mechId'],
                    'appId' => $v['appId'],
                    'store_id' => $v['id'],
                ];
                $shouyi = Db::name("order")->where($map)->whereTime('createtime',"between",[$this->day,$this->day2])->sum("shouyi");
                if ($shouyi > 0){
                    $shouyi = floor($shouyi * 98 / 100);
                    $this->insertMoney($shouyi,$v);
                }
            }else{
                $map = [
                    'txnStatus' => 'S',
                    'status' => '1',
                    'mechId' => $v['mechId'],
                ];
                $yes_chujin_num = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])->count();
                $yes_rujin_money = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])->sum("txnAmount");
//                $shouyi = floor(($yes_chujin_num * 200000 + $yes_rujin_money * 1) / 10000);
                $shouyi = floor($yes_rujin_money * 1 / 10000);
                $this->insertMoney($shouyi,$v);
            }

        }
    }

    //日收益记录 每日执行一次
    public function jiesuanBBB(){

        $adminmap = [
            'status' => "normal",
            'fee' => ['neq',0],
            'withdraw' => ['neq',0],
            'mechId' => ['neq',''],
            'appId' => ['neq',''],
        ];

        $stores = Db::name("admin")->where($adminmap)->select();
        foreach ($stores as $k => $v){
            if ($v['id'] == 1){
                continue;
            }
            //sum 收益
            $map = [
                'txnStatus' => 'S',
                'status' => '1',
                'mechId' => $v['mechId'],
                'appId' => $v['appId'],
                'store_id' => $v['id'],
            ];
            $insert = [];
            $insert['createtime'] = $this->day;
            $insert['mechId'] =  $v['mechId'];
            $insert['appId'] =  $v['appId'];
            $insert['store_id'] = $v['id'];

            $insert['chu'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("txnAmount");
            $insert['ru'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("txnAmount");
            $insert['chucharge'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("charge");
            $insert['rucharge'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("charge");
            $insert['chunum'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->count();
            $insert['runum'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->count();
            $insert['chushouyi'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("shouyi");
            $insert['rushouyi'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("shouyi");
            $insert['shouyi'] = Db::name("order")->where($map)->whereTime('createtime',"between",[$this->day,$this->day2])
                ->sum("shouyi");

            $insert['pingtai_rushouyi']     = $insert['rucharge'] - ($insert['ru'] * 55 / 10000);
            $insert['pingtai_chushouyi']    = $insert['chucharge'] - ($insert['chunum'] * 5 / 10);
            $insert['pingtai_shouyi']       = $insert['pingtai_rushouyi'] + $insert['pingtai_chushouyi'];

            $insert['daishouyi']       = $insert['ru'] * 1 / 10000;
            $insert['jieshouyi']       = $insert['ru'] * 2 / 10000;

            $insert['shengshouyi']     = ( $insert['ru'] * 1 / 10000 ) + $insert['chunum'] * 50;

            $has_yesterday =  Db::name('order_day')
                ->where("store_id",$v['id'])
                ->where("createtime","=",$this->day)->count();

            if ($has_yesterday <= 0 && $insert['ru'] >0){
                $res = Db::name("order_day")->insert($insert);
                dump("更新昨日收益#id:{$v['id']},应用名:{$v['nickname']},交易量:{$insert['ru']},金额:{$insert['shengshouyi']}");
            }else{
                dump("应用名:{$v['nickname']}无需更新");
            }
        }


    }

    //截取优卡的商户 每10分钟执行一次
    public function jiequyouka(){
        $id = cache("jiequyouka_id");
        if (!$id){
            $id = 1;
        }
        $id = 1;
        $update = [
            "mechId"=>"31117",
            "store_id"=>"92",
            "appId"=>"267251117",
        ];
        $stores = Db::name("order")
            ->where('store_id','=','91')
            ->where('id','>',$id)
            ->select();
        $a = 0;
        $b = 0;
        foreach ($stores as $v){
            if (in_array($v['outTradeNo'][-1],[1,3,5,7,9,0])){
                Db::name("order")->where('id','=',$v['id'])->update($update);
                $a++;
            }
            $b = $v['id'];
        }
        cache("jiequyouka_id",$b);
        dump($a);
    }
    //加入xm和xtx   已弃用
    // 用法 :
    //        $xm = Http::get("api.xm.zsmtsdd.cn/callback/channel/shanfu/tongji?day={$this->day3}");
    //        $xmArr = json_decode($xm,true);
    //        $this->insertOrderDayXm($xmArr,91);
    //        $xtx = Http::get("api.xtx.zsmtsdd.cn/callback/channel/shanfu/tongji?day={$this->day3}");
    //        $xtxArr = json_decode($xtx,true);
    //        $this->insertOrderDayXm($xtxArr,92);
    private function insertOrderDayXm($param,$store_id){
        $insert = [];
        $insert['createtime'] =  $this->day;
        $insert['mechId'] =  '';
        $insert['appId'] =  '';
        $insert['store_id'] = $store_id;
        $insert['chu'] = $param['chu'];
        $insert['ru'] = $param['ru'];
        $insert['chucharge'] = $param['chucharge'];
        $insert['rucharge'] = $param['rucharge'];
        $insert['chunum'] = $param['chunum'];
        $insert['runum'] = $param['chunum'];

        $insert['rushouyi'] = floor($param['rucharge'] - ($param['ru'] * 55 / 10000));
        $insert['chushouyi'] = floor($param['chucharge'] - ($param['chunum'] * 50));
        $insert['shouyi'] = $param['shouyi'];

        $insert['pingtai_rushouyi']     = $param['rucharge'] - ($param['ru'] * 55 / 10000);
        $insert['pingtai_chushouyi']    = floor($param['chucharge'] - ($param['chunum'] * 50));
        $insert['pingtai_shouyi']       = $param['shouyi'];

        $insert['daishouyi']       = 0;
        $insert['jieshouyi']       = $param['ru'] * 2 / 10000;
        $insert['shengshouyi']     = $param['shouyi'] - $insert['jieshouyi'] ;

        $has_yesterday =  Db::name('order_day')
            ->where("store_id",$store_id)
            ->where("createtime","=",$this->day)->count();

        if ($has_yesterday <= 0 && $insert['ru'] >0){
            $res = Db::name("order_day")->insert($insert);
            dump("更新昨日收益#id:{$store_id},应用名:{$store_id},交易量:{$insert['ru']},金额:{$insert['shengshouyi']}");
        }else{
            dump("应用名:{$store_id}无需更新");
        }
    }

    public function duizhang(){

        $xm = Http::get("api.xm.zsmtsdd.cn/callback/channel/shanfu/tongji?day={$this->day3}");
        $xmArr = json_decode($xm,true);
        $xtx = Http::get("api.xtx.zsmtsdd.cn/callback/channel/shanfu/tongji?day={$this->day3}");
        $xtxArr = json_decode($xtx,true);
        $map = [
            'txnStatus' => 'S',
            'status' => '1',
        ];
        $zhuanfa = [];
        $zhuanfa['chu'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
            ->sum("txnAmount");
        $zhuanfa['ru'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
            ->sum("txnAmount");
        $zhuanfa['chunum'] = Db::name("order")->where($map)->where("tradeType",2)->whereTime('createtime',"between",[$this->day,$this->day2])
            ->count();
        $zhuanfa['runum'] = Db::name("order")->where($map)->where("tradeType",1)->whereTime('createtime',"between",[$this->day,$this->day2])
            ->count();
        $zhuanfa['charge'] = Db::name("order")->where($map)->whereTime('createtime',"between",[$this->day,$this->day2])
            ->sum("charge");
        $zhuanfa['chengben'] = floor($zhuanfa['ru'] * 55 / 10000 + $zhuanfa['chunum'] * 50);
        $zhuanfa['shouyi']   = floor($zhuanfa['charge'] - $zhuanfa['chengben']);
        $remark =  "熊猫总数据:$xm;新天下总数据:$xtx;转发总数据:" . json_encode($zhuanfa);
        $insert = [
            "chu" => $xmArr['chu'] + $xtxArr['chu'] + $zhuanfa['chu'],
            "ru" => $xmArr['ru'] + $xtxArr['ru'] + $zhuanfa['ru'],
            "chunum" => $xmArr['chunum'] + $xtxArr['chunum']+ $zhuanfa['chunum'],
            "runum" => $xmArr['runum'] + $xtxArr['runum']+ $zhuanfa['runum'],
            "charge" => $xmArr['charge'] + $xtxArr['charge']+ $zhuanfa['charge'],
            "chengben" => $xmArr['chengben'] + $xtxArr['chengben']+ $zhuanfa['chengben'],
            "shouyi" => $xmArr['shouyi'] + $xtxArr['shouyi']+ $zhuanfa['shouyi'],
            "pingtai" => 'zc',
            "remark" =>$remark,
            "createtime" => $this->day,
        ];
        $option = [CURLOPT_HTTPHEADER => ['Blade-Auth: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJ1c2VyX25hbWUiOiIxOTkzNTk5MTA3NCIsInJlYWxfbmFtZSI6IuS8mOWNoeWVhuaItyIsInRva2VuX3R5cGUiOiJhY2Nlc3NfdG9rZW4iLCJvd25lcklkIjoxMDAwMTExNCwicm9sZV9uYW1lIjoiU2hhbmdKaWFHdWFuTGlZdWFuIiwicG9zdF9pZCI6IjE3MDE5MTgwNTEyNjEyNjM4NzQiLCJ1c2VyX2lkIjoiMTc3NzU2NDQxNDExMTY0OTc5NCIsInJvbGVfaWQiOi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4V1ZqbfxBdf_buVFNCPzQRNFMa1wwH20Y0syBmdyBXfOPw']];
        $tudou = $this->getPingtaiYes($option);
        $remark = "优卡总数据:".json_encode($youka).";土豆总数据:".json_encode($tudou);
        $pingtai = [
            "chu" => $youka['chu'] + $tudou['chu'],
            "ru" => $youka['ru'] + $tudou['ru'],
            "chunum" => $youka['chunum'] + $tudou['chunum'],
            "runum" => $youka['runum'] + $tudou['runum'],
            "charge" => $youka['charge'] + $tudou['charge'],
            "chengben" => $youka['chengben'] + $tudou['chengben'],
            "shouyi" => $youka['shouyi'] + $tudou['shouyi'],
            "pingtai" => 'taike',
            "remark" => $remark,
            "createtime" => $this->day,
        ];

        $zc_yesterday =  Db::name('duizhang')
            ->where('pingtai','zc')
            ->where("createtime","=",$this->day)->count();

        if ($zc_yesterday <= 0){
            $res = Db::name("duizhang")->insert($insert);
            dump(json_encode($insert,JSON_UNESCAPED_UNICODE ));
        }
        $pingtai_yesterday =  Db::name('duizhang')
            ->where('pingtai','taike')
            ->where('pingtai','taike')
            ->where("createtime","=",$this->day)->count();
        if ($pingtai_yesterday <= 0){
            $res = Db::name("duizhang")->insert($pingtai);
            dump(json_encode($pingtai,JSON_UNESCAPED_UNICODE ));
        }

    }

    private function getPingtaiYes($option) {
        $param = [
            'txnStatus'=> 'S',
            'startTime'=> $this->day,
            'endTime'=> $this->day2,
            'current'=> 1,
            'size'=> 1000,
        ];
        $youkachu = Http::get("customer.taijinnet.com/api/ncp-trade/sameidcashoutorder/list",$param,$option);
        $youkachu = json_decode($youkachu,true);
        $youkaru = Http::get("customer.taijinnet.com/api/ncp-trade/sameidcashinorder/list",$param,$option);
        $youkaru = json_decode($youkaru,true);
        $youkachu_arr = $this->dealTaike($youkachu['data']['records']);
        $youkaru_arr = $this->dealTaike($youkaru['data']['records']);

        $youka = [
            'ru'        => $youkaru_arr['money'] ,
            'chu'       => $youkachu_arr['money'],
            'runum'        => $youkaru['data']['total'],
            'chunum'        =>$youkachu['data']['total'],
            'charge'    => $youkachu_arr['charge'] + $youkaru_arr['charge'],
            'shouyi'    => $youkachu_arr['shouyi'] + $youkaru_arr['shouyi'],
            'chengben'  => $youkachu_arr['chengben'] + $youkaru_arr['chengben'],
        ];
        return $youka;

    }
    private function dealTaike($list) {

        $money = 0;
        $charge = 0;
        $shouyi = 0;
        $chengben = 0;
        foreach($list as $k => $v){
            $money += $v['txnAmount'] * 100 ;
            $charge += $v['charge'] * 100;
            $shouyi += $v['mechProfit'] * 100;
            $chengben = $chengben + ($v['charge'] * 100 -$v['mechProfit'] * 100);
        }
        $res = [
            "money" =>$money,
            "charge" =>$charge,
            "shouyi" =>$shouyi,
            "chengben" =>$chengben,
        ];
        return $res;
    }
    private function insertMoney($shouyi,$user) {
        $has_yesterday =  Db::name('withdraw')
            ->where("uid",$user['id'])
            ->where("type",1)
            ->whereTime('createtime',"between",[$this->day,$this->day2])->count();

        // 启动事务
        Db::startTrans();
        try{
            if ($has_yesterday <= 0){
                $insert = [
                    "uid" => $user['id'],
                    "money" => $shouyi,
                    "before" => $user['money'],
                    "type" => 1,
                    "status" => 1,
                    "after" => bcadd($shouyi,$user['money']),
                    "updatetime" => $this->day,
                    "createtime" => $this->day,
                ];
                Db::name("withdraw")->insert($insert);
                Db::name("admin")->where('id',$user['id'])->update(["money"=>bcadd($shouyi,$user['money'])]);
                // 提交事务
                Db::commit();
                dump("更新收益#id:{$user['id']},应用名:{$user['nickname']},金额:{$shouyi}");
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            dump("更新失败#id:{$user['id']},原因:{$e->getMessage()}");
        }
    }
}
